package com.sys.common.config;

import com.sys.common.util.JwtUtil;
import com.sys.pojo.Permission;
import com.sys.pojo.Role;
import com.sys.service.RolePermissionService;
import com.sys.service.UserRoleService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import javax.annotation.Resource;
import java.util.List;

/**
 * 创建realm
 *
 * @author zjf
 * @date 2021/04/01
 */
public class MyRealm extends AuthorizingRealm {

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private RolePermissionService rolePermissionService;

    /**
     * 多重写一个support
     * 标识这个Realm是专门用来验证JwtToken
     * 不负责验证其他的token（UsernamePasswordToken）
     *
     * @param token
     * @return
     */
    @Override
    public boolean supports(AuthenticationToken token) {
        //这个token就是从过滤器中传入的jwtToken
        return token instanceof JwtToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        System.out.println("===============授权========================");
        JwtUtil jwtUtil = new JwtUtil();
        Integer uId = (Integer) jwtUtil.decode(principalCollection.toString()).get("uId");
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        //获得该用户角色
        List<Role> roles = userRoleService.getAllRole(uId);

        for (Role role : roles) {
            info.addRole(role.getRoleName());
        }

        //每个角色拥有的权限
        List<Permission> rolePermission = rolePermissionService.getRolePermissionPerms(roles);

        for (Permission permission : rolePermission) {
            info.addStringPermission(permission.getPerms());
        }
        System.out.println("当前登录用户拥有角色");
        System.out.println(info.getRoles());
        System.out.println("当前登录用户拥有权限");
        System.out.println(info.getStringPermissions());
        return info;
    }

    //认证

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        System.out.println("===============认证========================");
        String jwt = (String) authenticationToken.getPrincipal();
        if (jwt == null) {
            throw new NullPointerException("jwtToken不允许为空");
        }
        JwtUtil jwtUtil = new JwtUtil();

        if (!jwtUtil.isVerify(jwt)) {
            throw new UnknownAccountException();
        }
        return new SimpleAuthenticationInfo(jwt, jwt, "MyRealm");
    }
}
